package com.fenghuajueli.libbasecoreui.feedback;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ToastUtils;
import com.fenghuajueli.lib_pictureselect.PhotoSelectorBuilder;
import com.fenghuajueli.lib_pictureselect.config.PhotoConfig;
import com.fenghuajueli.lib_pictureselect.entity.SelectMediaEntity;
import com.fenghuajueli.lib_pictureselect.interfaces.OnSelectResultListener;
import com.fenghuajueli.libbasecoreui.BaseApplication;
import com.fenghuajueli.libbasecoreui.R;
import com.fenghuajueli.libbasecoreui.adapter.PictureAdapter;
import com.fenghuajueli.libbasecoreui.adapter.XuqiuAdapter;
import com.fenghuajueli.libbasecoreui.constants.AppConfigInfo;
import com.fenghuajueli.libbasecoreui.databinding.ActivityTwoFeedbackWhiteBinding;
import com.fenghuajueli.libbasecoreui.user.UserInfoUtils;
import com.fenghuajueli.libbasecoreui.utils.MyStatusBarUtils;
import com.fenghuajueli.libbasecoreui.utils.QuickClickUtils;
import com.fenghuajueli.libbasecoreui.widget.CustomProgressDialog;
import com.ll.permission.AllowPermissionUseCase;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class TwoFeedbackActivity extends AppCompatActivity implements View.OnClickListener {
    private ActivityTwoFeedbackWhiteBinding binding;
    private Disposable dispose;
    //问题类型 使用疑问 bug反馈 会员问题
    private int feedback_type = 1;
    //手机型号
    private String phoneType = "";
    //应用商店
    private String appStore = "";
    //问题描述
    private String questionDes = "";
    //联系方式
    private String weChat = "", QQ = "", phoneNum = "";
    //上传图片的列表
    private String picPath;
    private ArrayList<String> picData = new ArrayList<>();
    private PictureAdapter adapter;
    private ArrayList<String> picUrl = new ArrayList<>();

    private CustomProgressDialog loadingDialog;
    public static final int FEEDBACK_START = 0x01;
    public static final int FEEDBACK_SUCCESS = 0x02;
    public static final int FEEDBACK_FAILED = 0x03;
    public static final int LOAD_SUCCESS = 0x04;
    public static final int DEMAND_SUCCESS = 0x05;
    public static final int DEMAND_CANCEL = 0x06;
    public static final int DEMAND_DISSMISS = 0x07;
    public static final int DEMAND_LAYOUT_MISS = 0x08;

    private String feedback = "cms/feedback";
    private String demand = "survey";
    //需求列表
    private XuqiuAdapter xuqiuAdapter;
    private ArrayList<XuqiuBean> xuqiuBeans = new ArrayList<>();
    //是否给需求点赞
    private int id, likes;

    //1默认皮肤是白色风格 2是黑色风格
    private int style = BaseApplication.getApplication().getDayNightMode();
    private LinearLayout layout_demand_success, layout_demand_cancel;

    private String imageurlHead = "http://ss.bscstorage.com/ijj-static/";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityTwoFeedbackWhiteBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        MyStatusBarUtils.setStatusBar(this, "#FFFFFF");
        ImageTools.initBsy();
        initView();
        GetDemand();

    }


    private void initView() {
        picData.clear();
        picUrl.clear();
        if (style == 2) {
            binding.onefeedbacklayout.setBackgroundColor(getResources().getColor(R.color.feedbackbg_black));
            binding.top.setBackgroundColor(getResources().getColor(R.color.feedbackbg_black));
            binding.middlelayout.setBackgroundColor(getResources().getColor(R.color.feedbackbg_black));
            binding.bottom.setBackgroundColor(getResources().getColor(R.color.feedbackbg_black));
            binding.view0.setBackgroundColor(getResources().getColor(R.color.feedbackbg_black));
            binding.view1.setBackgroundColor(getResources().getColor(R.color.feedbackbg_black));
            binding.view2.setBackgroundColor(getResources().getColor(R.color.feedbackbg_black));
            binding.view3.setBackgroundColor(getResources().getColor(R.color.feedbackbg_black));
            binding.view4.setBackgroundColor(getResources().getColor(R.color.feedbackbg_black));
            binding.imageback.setImageResource(R.mipmap.aa_icon_fh_white);
            binding.tvTitle.setTextColor(getResources().getColor(R.color.white));
            binding.tvQsType.setTextColor(getResources().getColor(R.color.white));
            binding.tvQsDes.setTextColor(getResources().getColor(R.color.white));
            binding.tvLxfs.setTextColor(getResources().getColor(R.color.white));
            binding.tvUpload.setTextColor(getResources().getColor(R.color.white));
            binding.tvWt1.setBackgroundResource(R.drawable.feedback_btn_qs_input_1_black);
            binding.tvWt2.setBackgroundResource(R.drawable.feedback_btn_qs_input_1_black);
            binding.tvWt3.setBackgroundResource(R.drawable.feedback_btn_qs_input_2_black);
            binding.tvWx.setBackgroundResource(R.drawable.feedback_btn_qs_input_1_black);
            binding.tvQq.setBackgroundResource(R.drawable.feedback_btn_qs_input_1_black);
            binding.tvPhone.setBackgroundResource(R.drawable.feedback_btn_qs_input_1_black);
            binding.tvQs1.setBackgroundResource(R.drawable.feedback_btn_question_sel_black);
            binding.tvQs2.setBackgroundResource(R.drawable.feedback_btn_question_nor_black);
            binding.tvQs3.setBackgroundResource(R.drawable.feedback_btn_question_nor_black);

        }
        binding.tvQs1.setOnClickListener(this);
        binding.tvQs2.setOnClickListener(this);
        binding.tvQs3.setOnClickListener(this);
        binding.imageChose.setOnClickListener(this);
        binding.tvCommit.setOnClickListener(this);
        adapter = new PictureAdapter(this, picData);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        binding.picList.setLayoutManager(linearLayoutManager);
        binding.picList.setAdapter(adapter);
        adapter.setOnItemClickLitener(new PictureAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(int position) {
                picData.remove(position);
                adapter.notifyDataSetChanged();
            }
        });

        xuqiuAdapter = new XuqiuAdapter(this, xuqiuBeans);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        binding.xqList.setLayoutManager(layoutManager);
        binding.xqList.setAdapter(xuqiuAdapter);
        xuqiuAdapter.setOnItemClickLitener(new XuqiuAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(int position) {
                int status = xuqiuBeans.get(position).getStatus();
                if (status == 0) {
                    xuqiuBeans.get(position).setStatus(1);
                    int like = xuqiuBeans.get(position).getLikes();
                    xuqiuBeans.get(position).setLikes(like + 1);
                    xuqiuAdapter.notifyDataSetChanged();
                    id = xuqiuBeans.get(position).getId();
                    likes = 1;
                } else {
                    xuqiuBeans.get(position).setStatus(0);
                    int like = xuqiuBeans.get(position).getLikes();
                    xuqiuBeans.get(position).setLikes(like - 1);
                    xuqiuAdapter.notifyDataSetChanged();
                    id = xuqiuBeans.get(position).getId();
                    likes = -1;
                }
                dianzan();
            }
        });

        layout_demand_success = findViewById(R.id.layout_demand_success);
        layout_demand_cancel = findViewById(R.id.layout_demand_cancel);

        binding.imageback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_qs_1) {
            changeType(1);
        } else if (id == R.id.tv_qs_2) {
            changeType(2);
        } else if (id == R.id.tv_qs_3) {
            changeType(3);
        } else if (id == R.id.tv_commit) {
            changePicData();
        } else if (id == R.id.image_chose) {
            applyPermission();
        }
    }

    /**
     * 申请权限
     */
    private void applyPermission() {
        AllowPermissionUseCase.useGalleryImages(
                this,
                "相册权限",
                "用于反馈图片上传功能，需要访问您的相册权限，如若拒绝，将无法使用上述功能。",
                "相册权限：该功能需要相册权限才可以正常运行，用于上传反馈图片。",
                "feedback",
                "请先申请相册权限!",
                () -> {
                    chose();
                    return null;
                });
    }

    //选择图片
    private void chose() {
        PhotoSelectorBuilder.builder(this)
                .mode(PhotoConfig.Mode.PHOTO)
                .isCopyToPrivate(false)
                .maxCount(9)
                .minCount(1)
                .listener(new OnSelectResultListener<List<SelectMediaEntity>>() {
                    @Override
                    public void onResult(List<SelectMediaEntity> data) {
                        if (data == null || data.size() == 0) {
                            return;
                        }
                        for (int i = 0; i < data.size(); i++) {
                            picPath = data.get(i).getTargetPath();
                            picData.add(picPath);
                        }
                        if (adapter != null) {
                            adapter.notifyDataSetChanged();
                        }
                    }
                });
    }

    //提交反馈
    private void commit() {
        phoneType = binding.tvWt1.getText().toString();
        appStore = binding.tvWt2.getText().toString();
        questionDes = binding.tvWt3.getText().toString();
        weChat = binding.tvWx.getText().toString();
        QQ = binding.tvQq.getText().toString();
        phoneNum = binding.tvPhone.getText().toString();
        mHandler.sendEmptyMessage(FEEDBACK_START);
        if (UserInfoUtils.getInstance().getUserInfoEntity() == null) {
            mHandler.sendEmptyMessageDelayed(FEEDBACK_SUCCESS, 2000);
            return;
        }
        String access_token = UserInfoUtils.getInstance().getUserInfoEntity().getToken();
        String feedback_msg = "";
        String feedback_img = "";
        String feedback_contact = "";
        FeedbackBean feedbackBean = new FeedbackBean();
        feedbackBean.setFeedback_type(feedback_type);
        JSONObject jsonObject1 = new JSONObject();
        try {
            jsonObject1.put("phoneType", phoneType);
            jsonObject1.put("appStore", appStore);
            jsonObject1.put("questionDes", questionDes);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        JSONObject jsonObject2 = new JSONObject();
        try {
            jsonObject2.put("weChat", weChat);
            jsonObject2.put("QQ", QQ);
            jsonObject2.put("phoneNum", phoneNum);
        } catch (JSONException e) {
            e.printStackTrace();
        }


        if (picUrl != null && picUrl.size() > 0) {
            for (int i = 0; i < picUrl.size(); i++) {
                feedback_img += picUrl.get(i) + ",";
            }
        }

        feedback_msg = jsonObject1.toString();
        feedback_contact = jsonObject2.toString();
        feedbackBean.setFeedback_img(feedback_img);
        feedbackBean.setFeedback_contact(feedback_contact);
        feedbackBean.setFeedback_msg(feedback_msg);
        JSONObject jsonObject3 = new JSONObject();
        try {
            jsonObject3.put("feedback_type", "" + feedbackBean.getFeedback_type());
            jsonObject3.put("feedback_msg", feedbackBean.getFeedback_msg());
            jsonObject3.put("feedback_img", feedbackBean.getFeedback_img());
            jsonObject3.put("feedback_contact", feedbackBean.getFeedback_contact());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        requst(AppConfigInfo.getUrl() + feedback, jsonObject3.toString(), 1);


    }

    private void dianzan() {
        if (QuickClickUtils.isFastClick()) {
            return;
        }
        JSONObject jsonObject3 = new JSONObject();
        try {
            jsonObject3.put("id", id);
            jsonObject3.put("likes", likes);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        requst(AppConfigInfo.getUrl() + demand, jsonObject3.toString(), 2);
    }

    /**
     * 选择问题类型
     *
     * @param type
     */
    public void changeType(int type) {
        feedback_type = type;
        if (style == 1) {
            if (type == 1) {
                binding.tvQs1.setBackgroundResource(R.drawable.feedback_btn_question_sel);
                binding.tvQs2.setBackgroundResource(R.drawable.feedback_btn_question_nor);
                binding.tvQs3.setBackgroundResource(R.drawable.feedback_btn_question_nor);
                binding.tvQs1.setTextColor(getResources().getColor(R.color.feedback_qs_sel));
                binding.tvQs2.setTextColor(getResources().getColor(R.color.feedback_qs_nor));
                binding.tvQs3.setTextColor(getResources().getColor(R.color.feedback_qs_nor));
            } else if (type == 2) {
                binding.tvQs2.setBackgroundResource(R.drawable.feedback_btn_question_sel);
                binding.tvQs1.setBackgroundResource(R.drawable.feedback_btn_question_nor);
                binding.tvQs3.setBackgroundResource(R.drawable.feedback_btn_question_nor);
                binding.tvQs2.setTextColor(getResources().getColor(R.color.feedback_qs_sel));
                binding.tvQs1.setTextColor(getResources().getColor(R.color.feedback_qs_nor));
                binding.tvQs3.setTextColor(getResources().getColor(R.color.feedback_qs_nor));
            } else if (type == 3) {
                binding.tvQs3.setBackgroundResource(R.drawable.feedback_btn_question_sel);
                binding.tvQs2.setBackgroundResource(R.drawable.feedback_btn_question_nor);
                binding.tvQs1.setBackgroundResource(R.drawable.feedback_btn_question_nor);
                binding.tvQs3.setTextColor(getResources().getColor(R.color.feedback_qs_sel));
                binding.tvQs2.setTextColor(getResources().getColor(R.color.feedback_qs_nor));
                binding.tvQs1.setTextColor(getResources().getColor(R.color.feedback_qs_nor));
            }
        } else if (style == 2) {
            if (type == 1) {
                binding.tvQs1.setBackgroundResource(R.drawable.feedback_btn_question_sel_black);
                binding.tvQs2.setBackgroundResource(R.drawable.feedback_btn_question_nor_black);
                binding.tvQs3.setBackgroundResource(R.drawable.feedback_btn_question_nor_black);
                binding.tvQs1.setTextColor(getResources().getColor(R.color.feedback_qs_sel));
                binding.tvQs2.setTextColor(getResources().getColor(R.color.feedback_qs_nor));
                binding.tvQs3.setTextColor(getResources().getColor(R.color.feedback_qs_nor));
            } else if (type == 2) {
                binding.tvQs2.setBackgroundResource(R.drawable.feedback_btn_question_sel_black);
                binding.tvQs1.setBackgroundResource(R.drawable.feedback_btn_question_nor_black);
                binding.tvQs3.setBackgroundResource(R.drawable.feedback_btn_question_nor_black);
                binding.tvQs2.setTextColor(getResources().getColor(R.color.feedback_qs_sel));
                binding.tvQs1.setTextColor(getResources().getColor(R.color.feedback_qs_nor));
                binding.tvQs3.setTextColor(getResources().getColor(R.color.feedback_qs_nor));
            } else if (type == 3) {
                binding.tvQs3.setBackgroundResource(R.drawable.feedback_btn_question_sel_black);
                binding.tvQs2.setBackgroundResource(R.drawable.feedback_btn_question_nor_black);
                binding.tvQs1.setBackgroundResource(R.drawable.feedback_btn_question_nor_black);
                binding.tvQs3.setTextColor(getResources().getColor(R.color.feedback_qs_sel));
                binding.tvQs2.setTextColor(getResources().getColor(R.color.feedback_qs_nor));
                binding.tvQs1.setTextColor(getResources().getColor(R.color.feedback_qs_nor));
            }
        }

    }


//    /**
//     * 显示系统等待框
//     */
//    public void showLoadingDialog() {
//        if (loadingDialog == null) {
//            loadingDialog = new CustomProgressDialog(this);
//            loadingDialog.setCancelable(false);
//        }
//        if (!loadingDialog.isShowing()) {
//            loadingDialog.show();
//        }
//    }
//
//    /**
//     * 显示系统等待框
//     */
//    public void showLoadingDialog(String tips) {
//        hideLoadingDialog();
//        loadingDialog = new CustomProgressDialog(this, tips);
//        loadingDialog.setCancelable(false);
//        if (!loadingDialog.isShowing()) {
//            loadingDialog.show();
//        }
//    }
//
//    /**
//     * 显示系统等待框
//     */
//    public void showLoadingDialog(String msg, boolean isShowProgress) {
//        hideLoadingDialog();
//        loadingDialog = new CustomProgressDialog(this, msg, isShowProgress);
//        loadingDialog.setCancelable(false);
//        if (!loadingDialog.isShowing()) {
//            loadingDialog.show();
//        }
//    }
//
//    /**
//     * 关闭等待框
//     */
//    public void hideLoadingDialog() {
//        if (loadingDialog != null) {
//            loadingDialog.dismiss();
//            loadingDialog = null;
//        }
//    }

    public void showToast(String content) {
        ToastUtils.showLong(content);
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case FEEDBACK_START:
                    showToast("反馈中...");
                    break;

                case FEEDBACK_SUCCESS:
//                    hideLoadingDialog();
                    showToast("反馈成功！");
                    break;

                case FEEDBACK_FAILED:
//                    hideLoadingDialog();
                    showToast("反馈失败！");
                    break;

                case LOAD_SUCCESS:
                    if (xuqiuAdapter != null) {
                        xuqiuAdapter.notifyDataSetChanged();
                    }
                    break;

                case DEMAND_CANCEL:

                    break;

                case DEMAND_SUCCESS:
                    if (likes == 1) {
                        layout_demand_success.setVisibility(View.VISIBLE);
                    } else {
                        layout_demand_cancel.setVisibility(View.VISIBLE);
                    }
                    break;

                case DEMAND_DISSMISS:
                    if (likes == 1) {
                        layout_demand_success.setVisibility(View.GONE);
                    } else {
                        layout_demand_cancel.setVisibility(View.GONE);
                    }

                    break;

                case DEMAND_LAYOUT_MISS:
                    binding.layoutDemand.setVisibility(View.GONE);
                    break;
            }
        }
    };


    //发送请求的地址和数据
    public void requst(String url, String content, final int position) {
        System.out.println("uurl========" + url);
        MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
        Request request = new Request.Builder()
                .url(url)
                .addHeader("token", UserInfoUtils.getInstance().getUserInfoEntity().getToken())
                .post(RequestBody.create(mediaType, content))
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("onResponse========" + e.getMessage());
                if (position == 1) {
                    mHandler.sendEmptyMessageDelayed(FEEDBACK_FAILED, 2000);
                } else if (position == 2) {

                }


            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                if (position == 1) {
                    try {
                        JSONObject jsonObject = new JSONObject(res);
                        int code = jsonObject.getInt("code");
                        if (code == 200) {
                            mHandler.sendEmptyMessageDelayed(FEEDBACK_SUCCESS, 2000);
                        } else {
                            mHandler.sendEmptyMessageDelayed(FEEDBACK_FAILED, 2000);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else if (position == 2) {
                    try {
                        JSONObject jsonObject = new JSONObject(res);
                        int code = jsonObject.getInt("code");
                        if (code == 200) {
                            mHandler.sendEmptyMessage(DEMAND_SUCCESS);
                            mHandler.sendEmptyMessageDelayed(DEMAND_DISSMISS, 1000);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }


            }
        });
    }


    public void changePicData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (picData != null && picData.size() > 0) {
                    for (int i = 0; i < picData.size(); i++) {
                        picUrl.add(imageurlHead + ImageTools.getUrl(TwoFeedbackActivity.this, picData.get(i)));
                    }
                }
                commit();
            }
        }).start();

    }

    //获取需求列表
    public void GetDemand() {
        if (UserInfoUtils.getInstance().getUserInfoEntity() == null) {
            binding.layoutDemand.setVisibility(View.GONE);
            return;
        }
        String token = UserInfoUtils.getInstance().getUserInfoEntity().getToken();
        String url = AppConfigInfo.getUrl() + demand;
        Request.Builder builder = new Request.Builder();
        builder.url(url).addHeader("token", token);
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = builder.build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("res============failed");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                System.out.println("ressss============" + res);
                parseDemand(res);
            }
        });
    }

    //解析需求列表
    private void parseDemand(String res) {
        try {
            JSONObject jsonObject = new JSONObject(res);
            int code = jsonObject.getInt("code");
            if (code == 200) {
                JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                int total = jsonObject1.getInt("total");
                if (total == 0) {

                    mHandler.sendEmptyMessage(DEMAND_LAYOUT_MISS);
                } else {
                    JSONArray jsonArray = jsonObject1.getJSONArray("list");
                    xuqiuBeans.clear();
                    for (int i = 0; i < jsonArray.length(); i++) {
                        XuqiuBean xuqiuBean = new XuqiuBean();
                        xuqiuBean.setId(jsonArray.getJSONObject(i).getInt("id"));
                        xuqiuBean.setCreate_time(jsonArray.getJSONObject(i).getString("create_time"));
                        xuqiuBean.setContent(jsonArray.getJSONObject(i).getString("content"));
                        xuqiuBean.setLikes(jsonArray.getJSONObject(i).getInt("likes"));
                        xuqiuBean.setStatus(0);
                        xuqiuBean.setOrder(jsonArray.getJSONObject(i).getInt("order"));
                        xuqiuBeans.add(xuqiuBean);
                    }
                    mHandler.sendEmptyMessage(LOAD_SUCCESS);
                }
            } else {
                binding.layoutDemand.setVisibility(View.GONE);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}
